package com.weiyuwqj.server.service.item.impl;


import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.model.BusItemAuto;
import com.weiyuwqj.api.model.BusItemAutoSort;
import com.weiyuwqj.api.model.vo.ItemAutoVo;
import com.weiyuwqj.api.service.BusItemAutoService;
import com.weiyuwqj.server.mapper.BusItemAutoMapper;
import com.weiyuwqj.server.mapper.BusItemAutoSortMapper;
import com.weiyuwqj.server.service.base.BaseServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/12/14.
 */
@Service("itemAutoService")
public class BusItemAutoServiceImpl extends BaseServiceImpl<BusItemAuto> implements BusItemAutoService {

    @Autowired
    private BusItemAutoMapper autoMapper;
    @Autowired
    private BusItemAutoSortMapper sortMapper;


    @Override
    public void deleteAutoByAutoId(Integer autoId,Integer userId) {
        autoMapper.deleteAutoByAutoId(autoId,userId);
    }

    @Override
    public void modifyAutoStatusByAutoId(BusItemAuto auto) {
        autoMapper.modifyAutoStatusByAutoId(auto);
    }

    @Override
    public void modifyAutoByAutoId(BusItemAuto auto) {
        autoMapper.modifyAutoByAutoId(auto);
    }
    /**
     * 添加自动投标及其对应的排序
     * @param auto
     */
    @Override
    public void addAuto(BusItemAuto auto){
//        if(autoMapper.selectByUserId(auto.getItemUserId())!=null ){
//            throw new CrowdException("");
//        }
        auto.setAddtime(new Date());
        auto.setUpdatetime(new Date());
        auto.setIsDelete(0);
        auto.setItemStatus(1);
        auto.setCountInvest(0);
        auto.setItemDayMin(auto.getItemDayMin()*30);
        auto.setItemDayMax(auto.getItemDayMax()*30);
        autoMapper.insertByReturnPrimaryKey(auto);

        BusItemAutoSort sort=new BusItemAutoSort();
        sort.setAutoId(auto.getId());
        sort.setUserId(auto.getItemUserId());
        sort.setSort(String.valueOf(new Date().getTime()));
        sortMapper.insert(sort);
    }

    @Override
    public Object getAutoByUserId(Integer userId) {
        ItemAutoVo autoVo = autoMapper.getAutoByUserId(userId);
        Map map = new HashMap();
        if(autoVo==null){
            map.put("result","fail");
        }else{
            BusItemAutoSort sort = sortMapper.getSortByAutoId(autoVo.getId());
            Integer rank = sortMapper.getRankingBySort(sort);
            autoVo.setSort(rank+1);
            map.put("result","success");
            map.put("data",autoVo);

        }
        return map;
    }

}
